package com.jh.hts_jdk.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;


public class CommandLine {
    private Process P;
    private Thread OutThread, ErrThread;
    private int ExitValue;

    /**
     * close the io stream when you redirect to a file
     */
    public int run(String CommandStr, PrintWriter Out, PrintWriter Error) throws IOException, InterruptedException {
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            P = Runtime.getRuntime().exec(new String[]{"cmd.exe", CommandStr});
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            P = Runtime.getRuntime().exec(new String[]{"sh", "-c", CommandStr});
        } else {
            System.err.println("无法确定当前系统");
            P = Runtime.getRuntime().exec(CommandStr);
        }
        OutThread = new Thread(() -> {
            try {
                String line;
                BufferedReader bufferedReaderIn = new BufferedReader(new InputStreamReader(P.getInputStream()));
                while ((line = bufferedReaderIn.readLine()) != null) {
                    if (Out != null) {
                        Out.print(line + "\n");
                        Out.flush();
                    }
                }
                bufferedReaderIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        ErrThread = new Thread(() -> {
            try {
                String line;
                BufferedReader bufferedReaderIn = new BufferedReader(new InputStreamReader(P.getErrorStream()));
                while ((line = bufferedReaderIn.readLine()) != null) {
                    if (Error != null) {
                        Error.print(line + "\n");
                        Error.flush();
                    }
                }
                bufferedReaderIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        OutThread.start();
        ErrThread.start();
        OutThread.join();
        ErrThread.join();
        ExitValue = P.waitFor();
        return ExitValue;
    }

    public int run(String CommandStr) throws IOException, InterruptedException {
        return run(CommandStr, null, null);
    }

    public void interrupt() {
        P.destroy();
    }

    public static void example() {
        String comLine = "ls -a | grep md";
        StringWriter out = new StringWriter();
        StringWriter err = new StringWriter();
        try {
            new CommandLine().run(comLine, new PrintWriter(out), new PrintWriter(err));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(out);
        System.err.println(err);
    }
}